export const wordArrangement = {
  data() {
    return {
      currentSentenceIndex: 0,
      isPlaying: false,
      // 练习相关数据
      userWords: [],
      originalWords: [],
      correctWords: [],
      clickCount: 0,
      hintCount: 0,
      isCompleted: false,
      sentenceEndTime: 0 // 句子结束时间
    }
  },
  computed: {
    currentSentence() {
      if (!this.lesson || !this.lesson.content || this.lesson.content.length === 0) {
        return { english: '', chinese: '' }
      }
      this.$nextTick(() => {
        this.initExercise()
      })
      return this.lesson.content[this.currentSentenceIndex] || { english: '', chinese: '' }
    },

    wordCount() {
      return this.correctWords.length
    },

    accuracy() {
      if (this.clickCount === 0) return 0
      // 简化的准确率计算：100% - (错误次数 / 总点击次数) * 100
      const errorCount = this.hintCount // 简化处理，以提示次数作为错误次数
      return Math.max(0, Math.round(100 - (errorCount / this.clickCount) * 100))
    },

    completion() {
      // 计算完成度：已完成句子数 / 总句子数
      const completedSentences = this.currentSentenceIndex + (this.isCompleted ? 1 : 0)
      return Math.round((completedSentences / this.lesson.content.length) * 100)
    }
  },
  async mounted() {
    const lessonId = this.$route.params.id
    await this.loadLesson(lessonId)

    // Check for sentence_id parameter and set current sentence index
    const sentenceId = this.$route.query.sentence_id
    if (sentenceId && !isNaN(sentenceId) && sentenceId > 0) {
      // Convert to 0-based index
      const index = parseInt(sentenceId) - 1
      // Make sure it's within bounds
      if (index < this.lesson.content.length) {
        this.currentSentenceIndex = index
        // Initialize exercise for the specified sentence
        this.$nextTick(() => {
          this.initExercise()
        })
      }
    }
  },
  beforeUnmount() {
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }
  },
  methods: {
    initExercise() {
      // 获取当前句子的英文文本
      if (!this.currentSentence) {
        return;
      }
      const sentenceText = this.currentSentence.english
      // 将句子拆分为单词，保留标点符号
      const words = this.extractWords(sentenceText)

      // 创建正确单词数组
      this.correctWords = words.map((word, index) => ({
        text: word,
        index: index,
        isCorrect: true
      }))

      // 创建乱序的原始单词数组
      this.originalWords = [...this.correctWords]
        .sort(() => Math.random() - 0.5) // 随机打乱
        .map((word, index) => ({
          ...word,
          tempId: `orig-${index}-${Date.now()}` // 临时ID用于拖拽
        }))

      // 用户区域初始为空
      this.userWords = []
      this.isCompleted = false
    },

    // 提取句子中的单词，使用空格分割但保留标点符号
    extractWords(sentence) {
      // 直接按空格分割，保留所有字符包括标点
      return sentence.split(' ').filter(word => word.length > 0)
    },

    playPrevious() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--
        this.initExercise()
      }
    },

    togglePlayback() {
      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.playCurrentSentence()
      }
    },

    playNext() {
      if (this.currentSentenceIndex < this.lesson.content.length - 1) {
        this.currentSentenceIndex++
        this.initExercise()
      }
    },

    playCurrentSentence() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        this.audio.currentTime = sentence.startTime
        this.sentenceEndTime = sentence.endTime
        this.audio.play()
        this.isPlaying = true
      }
    },

    pauseAudio() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
    },

    onAudioTimeUpdate() {
      // 检查是否到达句子结束时间
      if (this.isPlaying && this.audio && this.audio.currentTime >= this.sentenceEndTime) {
        this.audio.pause()
        this.isPlaying = false
      }
    },

    onAudioEnded() {
      this.isPlaying = false
    },

    changeSpeed(speed) {
      if (this.audio) {
        this.audio.playbackRate = speed
      }
    },

    onWordMove() {
      this.clickCount++
      this.checkCompletion()
    },

    checkCompletion() {
      // 检查用户排列是否正确
      if (this.userWords.length === this.correctWords.length) {
        const isCorrect = this.userWords.every((word, index) =>
          word.text.toLowerCase() === this.correctWords[index].text.toLowerCase()
        )

        if (isCorrect) {
          this.isCompleted = true
        }
      }
    },

    showHint() {
      this.hintCount++
      // 如果用户排列中有错误，高亮显示用户区域
      let hasError = false
      for (let i = 0; i < this.userWords.length; i++) {
        if (this.userWords[i].text.toLowerCase() !== this.correctWords[i].text.toLowerCase()) {
          hasError = true
          break
        }
      }

      if (hasError) {
        // 如果已有错误，只需要高亮用户区域（红色边框）
        const userWordsArea = document.querySelector('.user-words-area')
        if (userWordsArea) {
          userWordsArea.classList.add('error-highlight')
          // 3秒后移除高亮
          setTimeout(() => {
            userWordsArea.classList.remove('error-highlight')
          }, 3000)
        }
        return
      }

      // 如果没有错误，继续提示下一个单词
      if (this.userWords.length < this.correctWords.length) {
        // 获取下一个正确单词
        const nextIndex = this.userWords.length
        const nextCorrectWord = { ...this.correctWords[nextIndex] }

        // 将正确单词添加到用户区域
        this.userWords.push(nextCorrectWord)

        // 从原始区域中移除该单词
        const origIndex = this.originalWords.findIndex(word =>
          word.text.toLowerCase() === nextCorrectWord.text.toLowerCase())
        if (origIndex !== -1) {
          this.originalWords.splice(origIndex, 1)
        }
      }

      this.checkCompletion()
    },

    resetExercise() {
      this.initExercise()
      this.clickCount = 0
      this.hintCount = 0
    },

    checkAnswer() {
    }
  }
}